package com.huifaapp.mall.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.afinal.Constants;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.bean.TodaysSelectionBean;
import com.huifaapp.mall.bean.YouhuiParticularsBean;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.ShareUtils;
import com.huifaapp.mall.uitils.UtilsImage;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;

/**
 * Created by Administrator on 2017/12/14.
 */

public class TodaysSelectionFragment extends Fragment {
    private PullToRefreshGridView gv_home_today_share_weixin;
    public static List<Boolean> mChecked;
    List<TodaysSelectionBean.DataBean.ListBean> listb;
    ShareWeiXinListviewAdapter adapter;
    public static Map<Integer, Boolean> hmap;
    private TextView tv_quanbu_share;
    ArrayList<String> idlist = new ArrayList<>();
    private static final int SHARET_WXHY = 517;
    int wan = 0;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View viewLayout = inflater.inflate(R.layout.home_fragment_todays_selection, container, false);
        gv_home_today_share_weixin = (PullToRefreshGridView) viewLayout.findViewById(R.id.gv_home_today_share_weixin);
        tv_quanbu_share = (TextView) viewLayout.findViewById(R.id.tv_quanbu_share);
        gv_home_today_share_weixin.setMode(PullToRefreshBase.Mode.BOTH);//两端刷新
        gv_home_today_share_weixin.setSelected(true);
        gv_home_today_share_weixin.setScrollingWhileRefreshingEnabled(true);
        hmap = new HashMap<>();
        LoadStoreList(0, 0, Contig.listidid);
        gv_home_today_share_weixin.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                LoadStoreList(0, 0, Contig.listidid);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                LoadStoreList(1, listb.size()/10, Contig.listidid);
            }
        });


        new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                gv_home_today_share_weixin.setRefreshing(true);
                return false;
            }
        }).sendEmptyMessageDelayed(0, 200);

        tv_quanbu_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("数据Toady", Contig.checkedIndex + "-=====Contig.checkedIndex===id");
                if (Contig.checkedIndex.size() == 0) {
                    Toast.makeText(getActivity(), "没有选择，请选择再分享！", Toast.LENGTH_SHORT).show();
                } else {
                    for (int i = 0; i < Contig.checkedIndex.size(); i++)
                        idlist.add(listb.get(Contig.checkedIndex.get(i)).getId());

                    Log.e("数据Toady", idlist + "-===========id");


                    StringBuffer permission = new StringBuffer();
                    for (int i = 0; i < idlist.size(); i++) {
                        if (i == 0) {
                            permission.append(idlist.get(i));
                        } else {
                            permission.append("," + idlist.get(i));
                        }
                        Contig.listidid.add(idlist.get(i));

                    }
//                    LoadStoreList(0, 0, Contig.listidid);

                    ApiManager
                            .getInstance()
                            .getApiServer()
                            .getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(getActivity()), permission.toString())
                            .compose(ApiManager.<ShareImageBean>handlResult())
                            .subscribe(new ObserverCallback<ShareImageBean>(getActivity()) {
                                @Override
                                protected void onSuccessful(ShareImageBean resp) {

                                    saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);
                                    if (Contig.checkedIndex.size() > 0) {
                                        for (int a = 0; a < Contig.checkedIndex.size(); a++) {
                                            Contig.ShareList.add(listb.get(Contig.checkedIndex.get(a)).getId());
                                        }
                                    }
                                    adapter = new ShareWeiXinListviewAdapter(getActivity(), listb);
                                    gv_home_today_share_weixin.setAdapter(adapter);

                                }

                                @Override
                                protected void onError(String code, String errMsg) {
                                    ToastUtils.showShortSafe(errMsg);
                                }
                            });

                    idlist.clear();
                }
            }
        });
        return viewLayout;
    }


    private void saveImage(List<String> imageUrls, final String cconten, final int type) {

        Log.v("shiran", "------------saveImage------------");

        final LoadingDialog dialog = new LoadingDialog(getActivity());
        dialog.setContent("正在生成图片请稍后");


        Observable.just(imageUrls)
                .map(new Function<List<String>, List<String>>() {

                    @Override
                    public List<String> apply(List<String> list) throws Exception {

                        List<String> paths = new ArrayList<String>();
                        for (String s : list) {
                            FutureTarget<File> future = Glide.with(APP.getInstance())
                                    .load(s)
                                    .downloadOnly(500, 500);
                            File cacheFile = future.get();
                            String uuid = UUID.randomUUID().toString();
                            FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
                            String pat = savePath + uuid + ".jpg";
                            paths.add(pat);

                        }


                        return paths;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }
                    }

                    @Override
                    public void onNext(List<String> value) {
                        LogUtils.e(value);
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }

                        switch (type) {
                            case SHARET_WXHY:


                                ShareUtils.sharePicToFriendNoSDK(getActivity(), value);
//                                        ClipboardUtils.copyText(cconten);
//                                        ToastUtils.showShortSafe("内容已复制!");
                                break;
//                            case SHARET_WXPYQ:
//                                ShareUtils.share9PicsToWXCircle(getActivity(), "", value);
//                                break;
                            default:

                                break;
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }
                });

    }

    int length = 10;
    int start = 0;

    private void LoadStoreList(final int downorup, int starts, final ArrayList<String> idlist) {


        if (downorup == 0) {
            length = 10;
            start = 0;
        } else if (downorup == 1) {
            length = 10;
            start = starts;
        }
        String url = ApiManager.EVERYDAY_JINXUAN + "?start=" + start + "&length=" + length;
//        ;
        Log.e("WEB", "路径--" + url);
        HttpUtils http = new HttpUtils();
        //http://www.jhjvip.cn:8081/market/mobile/jd/index?
        http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
//              testTextView.setText(current + "/" + total);
                Log.e("数据", "数据-------" + current + "/" + total);
            }

            //
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
//                    textView.setText(responseInfo.result);
                gv_home_today_share_weixin.onRefreshComplete();
                Log.e("数据123", "数据d-------" + responseInfo.result);
                try {
                    Gson gson = new Gson();
                    TodaysSelectionBean list = gson.fromJson(responseInfo.result, TodaysSelectionBean.class);
                    if (list.getCode().equals("10000")) {

                        if (list.getData().getList() != null && list.getData().getList().size() > 0) {


                            if (downorup == 0) {
                                listb = list.getData().getList();
                                adapter = new ShareWeiXinListviewAdapter(getActivity(), listb);
                                gv_home_today_share_weixin.setAdapter(adapter);


                            } else {

                                listb.addAll(list.getData().getList());
                                if (listb.size() == 0) {
                                    gv_home_today_share_weixin.setVisibility(View.GONE);
                                }
                                adapter.notifyDataSetChanged();
                                // listView.getRefreshableView().setSelection(a);

                            }

                        }

                    } else {
                        Toast.makeText(getActivity(), list.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    Toast.makeText(getActivity(), "未知错误", Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                gv_home_today_share_weixin.onRefreshComplete();
            }
        });
    }
}

class ShareWeiXinListviewAdapter extends BaseAdapter {
    private Context context;
    private LayoutInflater inflater;
    private List<TodaysSelectionBean.DataBean.ListBean> list;
    private IWXAPI api;
    ArrayList<String> arrayList;
    private List<Boolean> isChecked;    //每个条目是否为选中
    private List<String> numbers;       //每个条目应显示的数字
    private List<Integer> checkedIndex;   //保存选中的下标
    private List<CheckBox> checkBox;      //保存选中的checkBox
    private int maxChecked = 9;       //最多选中几个
    private int checkedNumber = 0;    //选中的个数
    //        private int length = list.size();  //条目的总长
    ArrayList<String> idlist;

    ArrayList<Integer> a = new ArrayList<>();
    int aa = 0;

    public ShareWeiXinListviewAdapter(Context context, List<TodaysSelectionBean.DataBean.ListBean> list) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.list = list;
        this.idlist = idlist;
// 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(context, Constants.WX_APPID);
        api.registerApp(Constants.WX_APPID);
        arrayList = new ArrayList<String>();
        isChecked = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            isChecked.add(false);
        }
        numbers = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            numbers.add("");
        }
        checkedIndex = new ArrayList<>();
        checkBox = new ArrayList<>();

    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    public List<TodaysSelectionBean.DataBean.ListBean> getList() {
        return list;
    }

    public ShareWeiXinListviewAdapter setList(List<TodaysSelectionBean.DataBean.ListBean> list) {
        this.list = list;
        return this;
    }

    int ds = 0;

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.item_shareweixin_listview, null);
            holder = new ViewHolder();
            holder.iv_item_share_todaySeletion_shopimage = (ImageView) convertView.findViewById(R.id.iv_item_share_todaySeletion_shopimage);
            holder.tv_share_today_name = (TextView) convertView.findViewById(R.id.tv_share_today_name);
            holder.tv_share_today_yuanprice = (TextView) convertView.findViewById(R.id.tv_share_today_yuanprice);
            holder.tv_share_taday_redprice = (TextView) convertView.findViewById(R.id.tv_share_taday_redprice);
            holder.tv_share_xianprice = (TextView) convertView.findViewById(R.id.tv_share_xianprice);
            holder.tv_share_todaySeletion_yiqiangnum = (TextView) convertView.findViewById(R.id.tv_share_todaySeletion_yiqiangnum);
            holder.tv_lijishare_btn = (TextView) convertView.findViewById(R.id.tv_lijishare_btn);
            holder.tv_lijishare_btn_no = (TextView) convertView.findViewById(R.id.tv_lijishare_btn_no);
            holder.cb_checked = (CheckBox) convertView.findViewById(R.id.cb_checked_share);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //解决RecyclerView和checkBox问题
        holder.cb_checked.setTag(position);
        if (TodaysSelectionFragment.hmap.containsKey(position)) {
            holder.cb_checked.setChecked(TodaysSelectionFragment.hmap.get(position));
        } else {
            holder.cb_checked.setChecked(false);//true or false 都可以，看实际需求
        }
        final TodaysSelectionBean.DataBean.ListBean bean = list.get(position);
        Log.e("数据", "positionLIST=========" + bean);
        UtilsImage.uploadimageview(holder.iv_item_share_todaySeletion_shopimage, bean.getMainImageUrl(), "", context);
        holder.tv_share_today_name.setText("\t\t\t\t" + bean.getGoodsName());
        holder.tv_share_today_yuanprice.setText("原价¥" + bean.getPrice());
        holder.tv_share_taday_redprice.setText("红包券¥" + bean.getCouponMoney());
        holder.tv_share_xianprice.setText("" + bean.getConPrice());
        holder.tv_share_todaySeletion_yiqiangnum.setText("已抢" + bean.getTotalSales() + "件");
        holder.tv_lijishare_btn.setText("分享赚 ¥" + bean.getWlCommission());
        holder.tv_lijishare_btn_no.setText("分享赚 ¥" + bean.getWlCommission());
        holder.tv_lijishare_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ShopYouhuiShareActivity.class);
                intent.putExtra("id", bean.getId());
                context.startActivity(intent);
                holder.tv_lijishare_btn_no.setVisibility(View.VISIBLE);
                holder.tv_lijishare_btn.setVisibility(View.GONE);

            }
        });

        try {


            //  不要动
            holder.cb_checked.setChecked(isChecked.get(position));
            holder.cb_checked.setText(numbers.get(position));
            holder.cb_checked.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    boolean check;
                    if (checkedNumber < maxChecked) {
                        if (!isChecked.get(position)) {
                            checkedIndex.add(position);
                            checkBox.add(holder.cb_checked);
                            checkedNumber++;
                            setText();
                        } else {
                            clearText(position, holder.cb_checked);
                        }
                        check = !isChecked.get(position);
                    } else {
                        if (checkedNumber == maxChecked && isChecked.get(position)) {
                            clearText(position, holder.cb_checked);
                        } else {
                            Toast.makeText(context, "最多只能选" + maxChecked + "个", Toast.LENGTH_SHORT).show();
                        }
                        check = false;
                    }
                    isChecked.set(position, check);
                    holder.cb_checked.setChecked(isChecked.get(position));
                }
            });

            Contig.checkedIndex = checkedIndex;
//                //这个就是那个id  idlist集合
//                if(idlist.size()>0){
//                    for (int i=0;i<idlist.size();i++){
//                        Log.e("数据Toady",position+"aaa"+idlist.get(i));
//                        if(idlist.get(i).equals(bean.getId())){
//                            aa=1;
//                            Log.e("数据Toady","aaaaaa"+aa);
//                        }else{
//                            aa=0;
//                            Log.e("数据Toady","aaaaa"+aa);
//                        }
//
//                    }
//                    a.add(aa);
//                    Log.e("数据Toady","aaaaaa"+aa);
//                }
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }

//                if(aa==1){
//                    holder.tv_lijishare_btn_no.setVisibility(View.VISIBLE);
//                    holder.tv_lijishare_btn.setVisibility(View.GONE);
//                }else{
//                    holder.tv_lijishare_btn_no.setVisibility(View.GONE);
//                    holder.tv_lijishare_btn.setVisibility(View.VISIBLE);
//                }
        holder.tv_lijishare_btn_no.setVisibility(View.GONE);
        holder.tv_lijishare_btn.setVisibility(View.VISIBLE);
        for (int s = 0; s < Contig.ShareList.size(); s++) {
            if (list.get(position).getId().equals(Contig.ShareList.get(s))) {
                holder.tv_lijishare_btn_no.setVisibility(View.VISIBLE);
                holder.tv_lijishare_btn.setVisibility(View.GONE);
                Log.e("5647","youbianhua          "+list.get(position).getId());
                return convertView;

            }
        }

        return convertView;
    }


    public void clearText(int position, CheckBox cb_checked) {
        for (int i = 0; i < checkedIndex.size(); i++) {
            if (checkedIndex.get(i) == position) {
                numbers.set(position, "");
                checkedIndex.remove(i);
                checkBox.remove(i);
                break;
            }
        }
        checkedNumber--;
        setText();
        numbers.set(position, "");
        cb_checked.setText("");
    }

    public void setText() {
        for (int i = 0; i < checkedIndex.size(); i++) {
            numbers.set(checkedIndex.get(i), (i + 1) + "");
            checkBox.get(i).setText(numbers.get(checkedIndex.get(i)));

        }
    }


    class ViewHolder {
        private ImageView iv_item_share_todaySeletion_shopimage;
        private TextView tv_share_today_name;
        private TextView tv_share_today_yuanprice;
        private TextView tv_share_taday_redprice;
        private TextView tv_share_xianprice;
        private TextView tv_share_todaySeletion_yiqiangnum;
        private TextView tv_lijishare_btn;
        public TextView tv_lijishare_btn_no;
        public CheckBox cb_checked;

    }


}